package com.shengcheng.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shengcheng.constant.RedisConstant;
import com.shengcheng.entity.UserInfo;
import com.shengcheng.login.TingShuLogin;
import com.shengcheng.result.RetVal;
import com.shengcheng.service.UserInfoService;
import com.shengcheng.util.AuthContextHolder;
import com.shengcheng.vo.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * vip服务配置表 前端控制器
 * </p>
 *
 * @author bch
 * @since 2024-06-24
 */
@RestController
@RequestMapping("/api/user/wxLogin/")
public class WxLoginController {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(summary = "小程序授权登录")
    @GetMapping("wxLogin/{code}")
    public RetVal wxLogin(@PathVariable String code) throws Exception {
        //获取用户OpenId
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openid = sessionInfo.getOpenid();
        //判断数据库是否存在
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getWxOpenId,openid);
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        //用户不存在，存储数据库
        if (userInfo == null) {
            userInfo = new UserInfo();
            userInfo.setNickname("听有" + System.currentTimeMillis());
            userInfo.setWxOpenId(openid);
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            //是否为会员
            userInfo.setIsVip(0);
            userInfoService.save(userInfo);
        }
        //用户存在 存储在redis
        String uuid = UUID.randomUUID().toString().replaceAll("-", " ");
        String userKey = RedisConstant.USER_LOGIN_KEY_PREFIX + uuid;
        redisTemplate.opsForValue().set(userKey,userInfo,RedisConstant.USER_LOGIN_KEY_TIMEOUT,TimeUnit.SECONDS);
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("token",uuid);
        return RetVal.ok(resMap);

    }

    @TingShuLogin
    @Operation(summary = "获取用户个人信息")
    @GetMapping("getUserInfo")
    public RetVal getUserInfo(){
        Long userId = AuthContextHolder.getUserId();
        UserInfo user = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(user,userInfoVo);
        return RetVal.ok(userInfoVo);
    }
}
